package org.example.algorithm.graph;

public class AroundAreaSolution {
    public void solve(char[][] board) {
        if (board == null || board.length==0) {
            return;
        }
        int row = board.length;
        int column = board[0].length;
        if (row<=2 || column<=2) {
            return;
        }
        for (int i=0;i<row;i++) {
            dfs(board, i, 0);
            dfs(board, i, column - 1);
        }
        for (int j=0;j<column;j++) {
            dfs(board, 0, j);
            dfs(board, row-1, j);
        }

        for (int i=0;i<row;i++) {
            for (int j=0;j<column;j++) {
                if (board[i][j] == 'F') {
                    board[i][j] = 'O';
                } else if (board[i][j] == 'O') {
                    board[i][j] = 'X';
                }
            }
        }
    }

    private void dfs(char[][] board, int i, int j) {
        if (i<0 || i>board.length-1 || j<0 || j>board[0].length-1 || board[i][j] != 'O') {
            return;
        }
        board[i][j] = 'F';
        dfs(board, i-1, j);
        dfs(board, i+1, j);
        dfs(board, i, j-1);
        dfs(board, i, j+1);
    }

    public static void main(String[] args) {
        //char[][] board = {{'X','X','X','X'},{'X','O','O','X'},{'X','X','O','X'},{'X','O','X','X'}};
        char[][] board = {{'O','X','X','O','X'},{'X','O','O','X','O'},{'X','O','X','O','X'},{'O','X','O','O','O'},{'X','X','O','X','O'}};
        AroundAreaSolution aroundAreaSolution = new AroundAreaSolution();
        aroundAreaSolution.solve(board);
        for (int i=0;i<board.length;i++) {
            for (int j=0;j<board[0].length;j++) {
                System.out.print(board[i][j]);
            }
            System.out.println("");
        }
    }
}
